'use strict';
let fs = require('fs');
let path = require('path');
const api_dir = __dirname.replace(/\\/g, '/');
// read dir to get files

function router(app, dir, config) {
  let permissionObject = {};
  let apiObject = {};

  let current_dir = dir || api_dir;
  let results = fs.readdirSync(current_dir);

  results.forEach(item => {
    if (/\.r\.js$/.test(item)) {
      let apiFile = require(`${current_dir}/${item}`);
      let prefix = apiFile.prefix || '';
      delete apiFile.prefix;
      let _permission = {};
      let _apis = {};
      Object.keys(apiFile).forEach(key => {
        let _apipath;

        if (typeof apiFile[key] == 'object') {

          if (typeof apiFile[key].method == 'function') {
            _apipath = '/api' + path.resolve('api,', current_dir.split(api_dir)[1] || '', prefix, (apiFile[key].path || '').replace(/\\|\//, '')).replace(/^\w+\:/, '').replace(/\\/g, '/');
            console.log(key, '\t', _apipath);
            // app[key](_apipath, verifyAccessMid(apiFile[key]['apiName']), apiFile[key].mid || [], apiFile[key].method);
            app[key](_apipath, apiFile[key].method);
            Object.assign(_permission, apiFile[key].permission || {});
            let api = Object.assign(apiFile[key].des || {}, {
              api_name: apiFile[key].name,
              type: key,
              url: `${config.api_root || ''}${_apipath}`
            });
            Object.assign(_apis, {
              [apiFile[key]['name'] || prefix || key || apiFile[key]['permission']]: api
            });
          } else {
            for (let skey in apiFile[key]) {
              _apipath = '/api' + path.resolve('api', current_dir.split(api_dir)[1] || '', prefix, skey, (apiFile[key][skey].path || '').replace(/\\|\//, '')).replace(/^\w+\:/, '').replace(/\\/g, '/');
              console.log(key, '\t', _apipath);
              // app[key](_apipath, permissionCheck(apiFile[key][skey]['permission']), verifyAccessMid(apiFile[key][skey]['apiName']), apiFile[key][skey].mid || [], apiFile[key][skey].method);
              app[key](_apipath, apiFile[key][skey].mid || [], apiFile[key][skey].method);
              Object.assign(_permission, apiFile[key][skey].permission || {});
              let api = Object.assign(apiFile[key][skey].des || {}, {
                api_name: apiFile[key][skey].name,
                type: key,
                url: `${config.api_root || ''}${_apipath}`
              });
              // console.log(apiFile[key][skey]['name']);
              Object.assign(_apis, {
                [apiFile[key][skey]['name'] || skey || apiFile[key][skey]['permission']]: api
              });
            }
          }
        } else {
          _apipath = '/api' + path.resolve('api', current_dir.split(api_dir)[1] || '', prefix).replace(/^\w+\:/, '').replace(/\\/g, '/');
          app[key](_apipath, apiFile[key]);
          Object.assign(_permission, apiFile[key].permission || {});
        }
      });
      Object.assign(apiObject, _apis);
      Object.assign(permissionObject, _permission);
    } else if (!/\.js$/.test(item)) {
      let data = router(app, `${current_dir}/${item}`, config) || {};
      permissionObject[item] = data.permissionObject;
      apiObject[item] = data.apiObject;
    }
  });
  return {
    permissionObject,
    apiObject
  };
}


module.exports = function(app, config) {
  let {
    permissionObject,
    apiObject
  } = router(app, null, config);

  app.get('/apis-json', (req, res) => {
    res.json(apiObject);
  });


  return {
    apiObject,
    permissionObject
  };
};
